var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session')
var ueditor = require('ueditor')
var indexRouter = require('./routes/index');
var captchaRouter = require('./routes/captcha');
var cors = require('cors');
var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
// app.use(express.json());
app.use(express.json({ limit: '50mb' }))
app.use(express.urlencoded({ extended: false }));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(cors());

// session配置
app.use(session({
  secret: 'back_blog',
  resave: false,
  saveUninitialized: true,
  cookie: {
    maxAge: 1000 * 60 * 60 * 2 //指定登录的有效时长为2小时
  }
}))

// 登录拦截
app.get('*', (req, res, next) => {
  var authorname = req.sessionStore.authorname
  var path = req.path
  if (path == '/'|| path == '/addclassify' || path == '/manageclassify' || path == '/editclassify' ||  path == '/writeblogs' ||  path == '/manageblogs' ||  path == '/editblogs' || path == '/authorinfo' || path == '/peopleleaveword' || path == '/manageauthors' || path == '/editauthorinfo') {
    if (!authorname) {
      return res.redirect('/login')
    }
  }
  next()
})

// ueditor相关配置
app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'), function (req, res, next) {
  var imgDir = '/upload/pages/images/' //默认上传地址为图片
  var ActionType = req.query.action;
  if (ActionType === 'uploadimage' || ActionType === 'uploadfile' || ActionType === 'uploadvideo') {
    var file_url = imgDir;//默认上传地址为图片
    /*其他上传格式的地址*/
    if (ActionType === 'uploadfile') {
      file_url = '/upload/pages/files/'; //附件保存地址
    }
    if (ActionType === 'uploadvideo') {
      file_url = '/upload/pages/videos/'; //视频保存地址
    }
    res.ue_up(file_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
    res.setHeader('Content-Type', 'text/html');
  }
  //客户端发起图片列表请求
  else if (ActionType === 'listimage') {
    res.ue_list(imgDir);  // 客户端会列出 dir_url 目录下的所有图片
  }
  // 客户端发起其它请求
  else {
    res.setHeader('Content-Type', 'application/json');
    res.redirect('/ueditor/nodejs/config.json')
  }
}));


app.use('/', indexRouter);
app.use('/captcha', captchaRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;
